package org.example.project

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.FolderOpen
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
import javax.swing.JFileChooser
import javax.swing.filechooser.FileNameExtensionFilter

data class SearchResult(
    val fileName: String,
    val filePath: String,
    val matchCount: Int,
    val matches: List<String> = emptyList()
)

@Composable
fun App() {
    var selectedFiles by remember { mutableStateOf<List<File>>(emptyList()) }
    var searchText by remember { mutableStateOf("") }
    var searchResults by remember { mutableStateOf<List<SearchResult>>(emptyList()) }
    var isSearching by remember { mutableStateOf(false) }
    val coroutineScope = rememberCoroutineScope()

    MaterialTheme {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 标题
            Text(
                text = "GZ文件内容搜索器",
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold
            )

            // 文件选择区域
            Card(
                modifier = Modifier.fillMaxWidth(),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "已选择文件: ${selectedFiles.size}",
                            style = MaterialTheme.typography.titleMedium
                        )

                        Button(
                            onClick = {
                                val fileChooser = JFileChooser().apply {
                                    isMultiSelectionEnabled = true
                                    fileFilter = FileNameExtensionFilter("GZ Files", "gz")
                                }

                                if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                                    selectedFiles = fileChooser.selectedFiles.toList()
                                }
                            }
                        ) {
                            Icon(Icons.Filled.FolderOpen, contentDescription = null)
                            Spacer(Modifier.width(8.dp))
                            Text("选择GZ文件")
                        }
                    }

                    // 显示选中的文件列表
                    if (selectedFiles.isNotEmpty()) {
                        LazyColumn(
                            modifier = Modifier
                                .fillMaxWidth()
                                .heightIn(max = 100.dp)
                        ) {
                            items(selectedFiles) { file ->
                                Text(
                                    text = file.name,
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
                                    modifier = Modifier.padding(vertical = 2.dp)
                                )
                            }
                        }
                    }
                }
            }

            // 搜索区域
            Card(
                modifier = Modifier.fillMaxWidth(),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    OutlinedTextField(
                        value = searchText,
                        onValueChange = { searchText = it },
                        label = { Text("搜索文本") },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true
                    )

                    Button(
                        onClick = {
                            if (selectedFiles.isNotEmpty() && searchText.isNotBlank()) {
                                coroutineScope.launch {
                                    isSearching = true
                                    searchResults = searchInGzFiles(selectedFiles, searchText)
                                    isSearching = false
                                }
                            }
                        },
                        enabled = selectedFiles.isNotEmpty() && searchText.isNotBlank() && !isSearching,
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        if (isSearching) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                strokeWidth = 2.dp
                            )
                            Spacer(Modifier.width(8.dp))
                            Text("搜索中...")
                        } else {
                            Icon(Icons.Filled.Search, contentDescription = null)
                            Spacer(Modifier.width(8.dp))
                            Text("开始搜索")
                        }
                    }
                }
            }

            // 搜索结果区域
            if (searchResults.isNotEmpty()) {
                Card(
                    modifier = Modifier.fillMaxWidth().weight(1f),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "搜索结果 (找到 ${searchResults.count { it.matchCount > 0 }} 个匹配文件)",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )

                        Spacer(Modifier.height(8.dp))

                        LazyColumn(
                            modifier = Modifier.fillMaxWidth(),
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            items(searchResults.filter { it.matchCount > 0 }) { result ->
                                ResultItem(result)
                            }
                        }
                    }
                }
            } else if (!isSearching && searchResults.isEmpty() && selectedFiles.isNotEmpty() && searchText.isNotBlank()) {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.errorContainer
                    )
                ) {
                    Text(
                        text = "未找到匹配的内容",
                        modifier = Modifier.padding(16.dp),
                        color = MaterialTheme.colorScheme.onErrorContainer
                    )
                }
            }
        }
    }
}

@Composable
fun ResultItem(result: SearchResult) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant
        )
    ) {
        Column(
            modifier = Modifier.padding(12.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = result.fileName,
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Bold
                )

                Surface(
                    shape = androidx.compose.foundation.shape.RoundedCornerShape(12.dp),
                    color = MaterialTheme.colorScheme.primary
                ) {
                    Text(
                        text = "${result.matchCount} 次匹配",
                        modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                        color = MaterialTheme.colorScheme.onPrimary,
                        style = MaterialTheme.typography.labelSmall
                    )
                }
            }

            Text(
                text = result.filePath,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
            )

            // 显示前几个匹配的行
            if (result.matches.isNotEmpty()) {
                Spacer(Modifier.height(8.dp))
                Column {
                    result.matches.take(3).forEach { match ->
                        Text(
                            text = "• $match",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f),
                            modifier = Modifier.padding(start = 8.dp, bottom = 2.dp)
                        )
                    }
                    if (result.matches.size > 3) {
                        Text(
                            text = "... 还有 ${result.matches.size - 3} 行匹配",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.padding(start = 8.dp)
                        )
                    }
                }
            }
        }
    }
}

suspend fun searchInGzFiles(files: List<File>, searchText: String): List<SearchResult> = withContext(Dispatchers.IO) {
    files.map { file ->
        async {
            try {
                val matches = mutableListOf<String>()
                var matchCount = 0

                FileInputStream(file).use { fis ->
                    GzipCompressorInputStream(fis).use { gzis ->
                        BufferedReader(InputStreamReader(gzis, Charsets.UTF_8)).use { reader ->
                            reader.lineSequence().forEach { line ->
                                if (line.contains(searchText, ignoreCase = true)) {
                                    matchCount++
                                    if (matches.size < 10) { // 最多保存10个匹配行用于显示
                                        matches.add(line.trim().take(100)) // 限制每行长度
                                    }
                                }
                            }
                        }
                    }
                }

                SearchResult(
                    fileName = file.name,
                    filePath = file.absolutePath,
                    matchCount = matchCount,
                    matches = matches
                )
            } catch (e: Exception) {
                e.printStackTrace()
                SearchResult(
                    fileName = file.name,
                    filePath = file.absolutePath,
                    matchCount = 0,
                    matches = listOf("读取文件时出错: ${e.message}")
                )
            }
        }
    }.awaitAll()
}